package com.cma.typhoon.web.controller;

import com.cma.common.security.DESUtil;
import com.cma.common.utils.CookieUtil;
import com.cma.model.db.SysUser;
import com.cma.service.SysRoleService;
import com.cma.service.SysUserService;
import com.cma.typhoon.web.Constants;
import com.cma.typhoon.web.realm.StatelessToken;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by bai on 2017/1/8.
 */
@Controller
@RequestMapping("/authc")
public class LoginController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    /**
     * 登陆
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/dologin")
    @ResponseBody
    public Object dologin(Model model, HttpServletRequest request, SysUser user, HttpServletResponse response){
        Map<String,String> map=new HashMap<>();
        // 模拟登陆
//        model.addAttribute(Constants.PARAM_USERNAME,"18911301931");
//        model.addAttribute(Constants.PARAM_DIGEST,"123456");
        try {
            /*String key = DESUtil.encrypt("admin");
            String value = DESUtil.encrypt("123456");*/
            UsernamePasswordToken   up=new UsernamePasswordToken(user.getUserName(),user.getPassword());
            up.setRememberMe(true);
            Subject sub=SecurityUtils.getSubject();
            sub.login(up);
            if(sub.isAuthenticated()){
                sub.getSession().setAttribute("user",user.getUserName());
                map.put("code","0");
            }
           /* int expire = 30 * 24 * 3600;//七天

            CookieUtil.setCookie(response, null, Constants.PARAM_USERNAME, key, expire);
            CookieUtil.setCookie(response, null, Constants.PARAM_DIGEST, value, expire);*/
        }catch(Exception e){
            e.printStackTrace();
            map.put("code","1");
            map.put("data","登陆失败,用户名或密码错误");
        }
        return map;
    }
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/loginout")
    public String loginout(){
        Subject sub=SecurityUtils.getSubject();

        try{
            sub.logout();
            return "redirect:/";
        }catch (Exception e){
            return "redirect:/";
        }

    }
}
